﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PaperRenderingInterfaces;
using System.ComponentModel.Composition;
using DeepZoomPivotConstructor.PivotLib;
using System.Xml.Serialization;
using System.IO;

namespace CDSParser
{
    /// <summary>
    /// Parse a search list that comes back from CDS for figures attached to notes.
    /// </summary>
    [Export(typeof(IPaperRender))]
    [PaperRender("CDSFigureSearchList")]
    public class CDSFigureSearchList : IPaperRender
    {
        /// <summary>
        /// How we fetch stuff from the web.
        /// </summary>
        [Import]
        IWebAccess WebGetter { get; set; }

        /// <summary>
        /// Given a URL of a CDS search, render the figures associated with them all.
        /// </summary>
        /// <param name="renderAddress"></param>
        /// <returns></returns>
        public IEnumerable<PivotImage> Render(string renderAddress)
        {
            ///
            /// Get the complete data back for this search
            /// 

            XMLSchema.collectionType parsedResult = CDSUtilities.FetchParsedCDSMARKXML(WebGetter, renderAddress);

            ///
            /// Now, go through each one of these guys and find a CDS paper and try to render it!
            /// 

            return parsedResult.record.SelectMany(r => ParseCDSXMLForPaperID("CDSFiguresFromOnePaper", r));
        }

#pragma warning disable 0649
        [Import(typeof(IPaperRenderEngine))]
        private IPaperRenderEngine Engine;
#pragma warning restore 0649

        /// <summary>
        /// Given the XML, find the ID for a particular CDS paper, and then get that rendered.
        /// </summary>
        /// <param name="renderEngineName"></param>
        /// <param name="cdsRecord"></param>
        /// <returns></returns>
        private IEnumerable<PivotImage> ParseCDSXMLForPaperID(string renderEngineName, XMLSchema.recordType cdsRecord)
        {
            var goodClFlgs = from clf in cdsRecord.controlfield
                            where clf.tag == "001"
                            select clf.Value;
            var goodClFlg = goodClFlgs.FirstOrDefault();
            if (goodClFlg == null)
            {
                return Enumerable.Empty<PivotImage>();
            }
            return Engine.Render(renderEngineName, goodClFlg);
        }
    }
}
